{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Shuffle\n",
    "# 该算法会打乱列表元素的顺序，它主要会通过 Fisher-Yates 算法对新列表进行排序\n",
    "from copy import deepcopy\n",
    "from random import randint\n",
    "\n",
    "\n",
    "def shuffle(lst):\n",
    "    temp_lst = deepcopy(lst)\n",
    "    m = len(temp_lst)\n",
    "    while m:\n",
    "        m -= 1\n",
    "        i = randint(0, m)\n",
    "        temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]\n",
    "    return temp_lst\n",
    "\n",
    "\n",
    "foo = [1, 2, 3]\n",
    "shuffle(foo)  # [2,3,1] , foo = [1,2,3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表枚举\n",
    "list = [\"a\", \"b\", \"c\", \"d\"]\n",
    "for index, element in enumerate(list):\n",
    "    print(\n",
    "        \"Value\",\n",
    "        element,\n",
    "        \"Index \",\n",
    "        index,\n",
    "    )\n",
    "\n",
    "# ('Value', 'a', 'Index ', 0)\n",
    "# ('Value', 'b', 'Index ', 1)\n",
    "# ('Value', 'c', 'Index ', 2)\n",
    "# ('Value', 'd', 'Index ', 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 重复元素判定\n",
    "def all_unique(lst):\n",
    "    return len(lst) == len(set(lst))\n",
    "\n",
    "\n",
    "x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]\n",
    "y = [1, 2, 3, 4, 5]\n",
    "all_unique(x)  # False\n",
    "all_unique(y)  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 分块\n",
    "# 给定具体的大小，定义一个函数以按照这个大小切割列表。\n",
    "from math import ceil\n",
    "\n",
    "\n",
    "def chunk(lst, size):\n",
    "    return list(\n",
    "        map(\n",
    "            lambda x: lst[x * size : x * size + size],\n",
    "            list(range(0, ceil(len(lst) / size))),\n",
    "        )\n",
    "    )\n",
    "\n",
    "\n",
    "chunk([1, 2, 3, 4, 5], 2)\n",
    "# [[1,2],[3,4],5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 'a', 's', 34]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 压缩\n",
    "# 这个方法可以将布尔型的值去掉，例如(False, None, 0, \"\")，它使用 filter() 函数。\n",
    "def compact(lst):\n",
    "    return list(filter(bool, lst))\n",
    "\n",
    "\n",
    "compact([0, 1, False, 2, \"\", 3, \"a\", \"s\", 34])\n",
    "# [ 1, 2, 3, 'a', 's', 34 ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 展开列表\n",
    "# 将列表内的所有元素，包括子列表，都展开成一个列表。\n",
    "def spread(arg):\n",
    "    ret = []\n",
    "    for i in arg:\n",
    "        if isinstance(i, list):\n",
    "            ret.extend(i)\n",
    "        else:\n",
    "            ret.append(i)\n",
    "    return ret\n",
    "\n",
    "\n",
    "spread([1, 2, 3, [4, 5, 6], [7], 8, 9])  # [1,2,3,4,5,6,7,8,9]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 字典默认值\n",
    "\"\"\" \n",
    "通过 Key 取对应的 Value 值，可以通过以下方式设置默认值。\n",
    "如果 get() 方法没有设置默认值，那么如果遇到不存在的 Key，则会返回 None。\n",
    "\"\"\"\n",
    "d = {\"a\": 1, \"b\": 2}\n",
    "print(d.get(\"c\", 3))  # 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将两个列表转化为字典\n",
    "def to_dictionary(keys, values):\n",
    "    return dict(zip(keys, values))\n",
    "\n",
    "\n",
    "keys = [\"a\", \"b\", \"c\"]\n",
    "values = [2, 3, 4]\n",
    "print(to_dictionary(keys, values))\n",
    "# {'a': 2, 'c': 4, 'b': 3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 合并两个字典\n",
    "def merge_two_dicts(a, b):\n",
    "    c = a.copy()  # make a copy of a\n",
    "    c.update(b)  # modify keys and values of a with the ones from b\n",
    "    return c\n",
    "\n",
    "\n",
    "a = {\"x\": 1, \"y\": 2}\n",
    "b = {\"y\": 3, \"z\": 4}\n",
    "print(merge_two_dicts(a, b))\n",
    "# {'y': 3, 'x': 1, 'z': 4}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 检查重复项  如下代码将检查两个列表是不是有重复项。\n",
    "def has_duplicates(lst):\n",
    "    return len(lst) != len(set(lst))\n",
    "\n",
    "x = [1,2,3,4,5,5]\n",
    "y = [1,2,3,4,5]\n",
    "has_duplicates(x) # True\n",
    "has_duplicates(y) # False\n",
    "# 在 Python 3.5 或更高版本中，我们也可以用以下方式合并字典：\n",
    "def merge_dictionaries(a, b)\n",
    "   return {**a, **b}\n",
    "\n",
    "a = { 'x': 1, 'y': 2}\n",
    "b = { 'y': 3, 'z': 4}\n",
    "print(merge_dictionaries(a, b))\n",
    "# {'y': 3, 'x': 1, 'z': 4}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 字符元素组成判定\n",
    "from collections import Counter\n",
    "\n",
    "\n",
    "def anagram(first, second):\n",
    "    return Counter(first) == Counter(second)\n",
    "\n",
    "\n",
    "anagram(\"abcd3\", \"3acdb\")  # True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 语法糖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 交换值\n",
    "def swap(a, b):\n",
    "    return b, a\n",
    "\n",
    "\n",
    "a, b = -1, 14\n",
    "swap(a, b)  # (14, -1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打印 N 次字符串\n",
    "n = 2\n",
    "s = \"Programming\"\n",
    "\n",
    "print(s * n)\n",
    "# ProgrammingProgramming\n",
    "# 该代码块不需要循环语句就能打印 N 次字符串。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 大写第一个字母\n",
    "s = \"programming is awesome\"\n",
    "\n",
    "print(s.title())\n",
    "# Programming Is Awesome"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 解包\n",
    "# 如下代码段可以将打包好的成对列表解开成两组不同的元组。\n",
    "array = [[\"a\", \"b\"], [\"c\", \"d\"], [\"e\", \"f\"]]\n",
    "transposed = zip(*array)\n",
    "print(transposed)\n",
    "# [('a', 'c', 'e'), ('b', 'd', 'f')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 链式对比\n",
    "# 我们可以在一行代码中使用不同的运算符对比多个不同的元素。\n",
    "a = 3\n",
    "print(2 < a < 8)  # True\n",
    "print(1 == a < 2)  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 逗号连接\n",
    "# 下面的代码可以将列表连接成单个字符串，且每一个元素间的分隔方式设置为了逗号。\n",
    "hobbies = [\"basketball\", \"football\", \"swimming\"]\n",
    "\n",
    "print(\"My hobbies are: \" + \", \".join(hobbies))\n",
    "# My hobbies are: basketball, football, swimming"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 元音统计\n",
    "# 以下方法将统计字符串中的元音(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)的个数，它是通过正则表达式做的。\n",
    "import re\n",
    "\n",
    "\n",
    "def count_vowels(str):\n",
    "    return len(len(re.findall(r\"[aeiou]\", str, re.IGNORECASE)))\n",
    "\n",
    "\n",
    "count_vowels(\"foobar\")  # 3\n",
    "count_vowels(\"gym\")  # 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 首字母小写\n",
    "# 如下方法将令给定字符串的第一个字符统一为小写。\n",
    "def decapitalize(string):\n",
    "    return str[:1].lower() + str[1:]\n",
    "\n",
    "\n",
    "decapitalize(\"FooBar\")  # 'fooBar'\n",
    "decapitalize(\"FooBar\")  # 'fooBar'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 展开列表\n",
    "def spread(arg):\n",
    "    ret = []\n",
    "    for i in arg:\n",
    "        if isinstance(i, list):\n",
    "            ret.extend(i)\n",
    "        else:\n",
    "            ret.append(i)\n",
    "    return ret\n",
    "\n",
    "\n",
    "def deep_flatten(lst):\n",
    "    result = []\n",
    "    result.extend(\n",
    "        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))\n",
    "    )\n",
    "    return result\n",
    "\n",
    "\n",
    "deep_flatten([1, [2], [[3], 4], 5])  # [1,2,3,4,5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表之差\n",
    "# 该方法将返回第一个列表的元素，其不在第二个列表内。\n",
    "# 如果同时要反馈第二个列表独有的元素，还需要加一句 set_b.difference(set_a)。\n",
    "def difference(a, b):\n",
    "    set_a = set(a)\n",
    "    set_b = set(b)\n",
    "    comparison = set_a.difference(set_b)\n",
    "    return list(comparison)\n",
    "\n",
    "\n",
    "difference([1, 2, 3], [1, 2, 4])  # [3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过函数取差\n",
    "# 如下方法首先会应用一个给定的函数，然后再返回应用函数后结果有差别的列表元素。\n",
    "def difference_by(a, b, fn):\n",
    "    b = set(map(fn, b))\n",
    "    return [item for item in a if fn(item) not in b]\n",
    "\n",
    "\n",
    "from math import floor\n",
    "\n",
    "difference_by([2.1, 1.2], [2.3, 3.4], floor)  # [1.2]\n",
    "difference_by([{\"x\": 2}, {\"x\": 1}], [{\"x\": 1}], lambda v: v[\"x\"])\n",
    "# [ { x: 2 } ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 链式函数调用 你可以在一行代码内调用多个函数。\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "\n",
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "\n",
    "a, b = 4, 5\n",
    "print((subtract if a > b else add)(a, b))  # 9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 形式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 回文序列\n",
    "\"\"\" \n",
    "以下方法会检查给定的字符串是不是回文序列，它首先会把所有字母转化为小写，并移除非英文字母符号。\n",
    "最后，它会对比字符串与反向字符串是否相等，相等则表示为回文序列。\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def palindrome(string):\n",
    "    from re import sub\n",
    "\n",
    "    s = sub(\"[\\W_]\", \"\", string.lower())\n",
    "    return s == s[::-1]\n",
    "\n",
    "\n",
    "palindrome(\"taco cat\")  # True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 统计"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表元素频率\n",
    "def most_frequent(list):\n",
    "    return max(set(list), key=list.count)\n",
    "\n",
    "\n",
    "list = [1, 2, 1, 2, 3, 2, 1, 4, 2]\n",
    "most_frequent(list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 可视化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def visualize_results(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        result = func(*args, **kwargs)\n",
    "        plt.figure()\n",
    "        # Your visualization code here\n",
    "        plt.show()\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@visualize_results\n",
    "def analyze_and_visualize(data):\n",
    "    # Your combined analysis and visualization code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 控制流"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 异常流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def suppress_errors(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        try:\n",
    "            return func(*args, **kwargs)\n",
    "        except Exception as e:\n",
    "            print(f\"Error in {func.__name__}: {e}\")\n",
    "            return None\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@suppress_errors\n",
    "def preprocess_data(data):\n",
    "    # Your data preprocessing code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据格式验证\n",
    "def validate_input(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        # Your data validation logic here\n",
    "        if valid_data:\n",
    "            return func(*args, **kwargs)\n",
    "        else:\n",
    "            raise ValueError(\"Invalid data. Please check your inputs.\")\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@validate_input\n",
    "def analyze_data(data):\n",
    "    # Your data analysis code here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 日志输出\n",
    "# 将@log_results与日志库结合使用，以获得更高级的日志功能。\n",
    "def log_results(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        result = func(*args, **kwargs)\n",
    "        with open(\"results.log\", \"a\") as log_file:\n",
    "            log_file.write(f\"{func.__name__} - Result: {result}\\n\")\n",
    "        return result\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@log_results\n",
    "def calculate_metrics(data):\n",
    "    # Your metric calculation code here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Try else\n",
    "try:\n",
    "    2 * 3\n",
    "except TypeError:\n",
    "    print(\"An exception was raised\")\n",
    "else:\n",
    "    print(\"Thank God, no exceptions were raised.\")\n",
    "\n",
    "# Thank God, no exceptions were raised."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不使用 if-else 的计算子\n",
    "# 这一段代码可以不使用条件语句就实现加减乘除、求幂操作，它通过字典这一数据结构实现\n",
    "import operator\n",
    "\n",
    "action = {\n",
    "    \"+\": operator.add,\n",
    "    \"-\": operator.sub,\n",
    "    \"/\": operator.truediv,\n",
    "    \"*\": operator.mul,\n",
    "    \"**\": pow,\n",
    "}\n",
    "print(action[\"-\"](50, 25))  # 25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 类型确认\n",
    "def valid_output(result):\n",
    "    # 这里定义你的验证逻辑\n",
    "    # 例如，检查结果是否是期望的数据类型，或者是否满足特定的条件\n",
    "    return isinstance(result, expected_type)  # 假设 expected_type 是你期望的数据类型\n",
    "\n",
    "def validate_output(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        result = func(*args, **kwargs)\n",
    "        if valid_output(result):\n",
    "            return result\n",
    "        else:\n",
    "            raise ValueError(\"Invalid output. Please check your function logic.\")\n",
    "    return wrapper\n",
    "\n",
    "@validate_output\n",
    "def clean_data(data):\n",
    "    # Your data cleaning code here\n",
    "    return processed_data  # 假设 processed_data 是 clean_data 函数处理后的数据"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 重试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# retry 装饰器工厂函数，用于创建一个装饰器，该装饰器会在函数执行失败时重试指定次数\n",
    "def retry(max_attempts, delay):\n",
    "    # decorator 函数用于接收一个函数并返回一个包装函数\n",
    "    def decorator(func):\n",
    "        # wrapper 函数用于包装原始函数，增加重试逻辑\n",
    "        def wrapper(*args, **kwargs):\n",
    "            # 初始化尝试次数\n",
    "            attempts = 0\n",
    "            # 循环直到达到最大尝试次数\n",
    "            while attempts < max_attempts:\n",
    "                try:\n",
    "                    # 尝试执行原始函数\n",
    "                    return func(*args, **kwargs)\n",
    "                except Exception as e:\n",
    "                    # 如果发生异常，打印错误信息并等待一段时间后重试\n",
    "                    print(f\"Attempt {attempts + 1} failed. Retrying in {delay} seconds.\")\n",
    "                    attempts += 1\n",
    "                    time.sleep(delay)\n",
    "            # 如果所有尝试都失败，则抛出异常\n",
    "            raise Exception(\"Max retry attempts exceeded.\")\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "# 使用 retry 装饰器装饰 fetch_data_from_api 函数\n",
    "# 指定最大尝试次数为3次，每次尝试间隔2秒\n",
    "@retry(max_attempts=3, delay=2)\n",
    "def fetch_data_from_api(api_url):\n",
    "    # 这里应该是调用API并获取数据的代码\n",
    "    # 为了示例，我们模拟一个可能失败的操作\n",
    "    import random\n",
    "    if random.choice([True, False]):\n",
    "        raise Exception(\"Failed to fetch data.\")\n",
    "    else:\n",
    "        return \"Data fetched successfully.\"\n",
    "\n",
    "# 用例\n",
    "if __name__ == \"__main__\":\n",
    "    api_url = \"https://example.com/api/data\"\n",
    "    try:\n",
    "        data = fetch_data_from_api(api_url)\n",
    "        print(data)\n",
    "    except Exception as e:\n",
    "        print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 性能优化"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 时间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 执行时间\n",
    "import time\n",
    "\n",
    "start_time = time.time()\n",
    "\n",
    "a = 1\n",
    "b = 2\n",
    "c = a + b\n",
    "print(c)  # 3\n",
    "\n",
    "end_time = time.time()\n",
    "total_time = end_time - start_time\n",
    "print(\"Time: \", total_time)\n",
    "\n",
    "# ('Time: ', 1.1205673217773438e-05)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def timer(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        start_time = time.time()\n",
    "        result = func(*args, **kwargs)\n",
    "        end_time = time.time()\n",
    "        print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute.\")\n",
    "        return result\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@timer\n",
    "def my_data_processing_function():\n",
    "    # Your data processing code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 内存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "28\n"
     ]
    }
   ],
   "source": [
    "# 内存占用\n",
    "import sys\n",
    "\n",
    "variable = 30\n",
    "print(sys.getsizeof(variable))  # 24\n",
    "# 单位是字节（bytes）。这个函数会返回对象本身所占用的内存大小，不包括对象引用的其他对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 字节占用\n",
    "def byte_size(string):\n",
    "    return len(string.encode(\"utf-8\"))\n",
    "\n",
    "\n",
    "byte_size(\"😀\")  # 4\n",
    "byte_size(\"Hello World\")  # 11"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 缓存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def memoize(func):\n",
    "    cache = {}\n",
    "\n",
    "def wrapper(*args):\n",
    "        if args in cache:\n",
    "            return cache[args]\n",
    "        result = func(*args)\n",
    "        cache[args] = result\n",
    "        return result\n",
    "    return wrapper\n",
    "@memoize\n",
    "def fibonacci(n):\n",
    "    if n <= 1:\n",
    "        return n\n",
    "    return fibonacci(n - 1) + fibonacci(n - 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def debug(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print(f\"Debugging {func.__name__} - args: {args}, kwargs: {kwargs}\")\n",
    "        return func(*args, **kwargs)\n",
    "    \n",
    "    return wrapper\n",
    "@debug\n",
    "def complex_data_processing(data, threshold=0.5):\n",
    "    # Your complex data processing code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 维护"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 处理废弃的函数\n",
    "import warnings\n",
    "\n",
    "def deprecated(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        warnings.warn(f\"{func.__name__} is deprecated and will be removed in future versions.\", DeprecationWarning)\n",
    "        return func(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "@deprecated\n",
    "def old_data_processing(data):\n",
    "    # Your old data processing code here"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "science39",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
